package exam.business.service;

import java.util.Date;
import java.util.List;

import exam.common.constant.ResultPort;
import exam.common.key.KeyQuestion;
import exam.common.util.NullCheckUtil;
import exam.model.dao.TAnswerDAO;
import exam.model.dao.TQuestionDAO;
import exam.model.entity.TAnswerEntity;
import exam.model.entity.TQuestionEntity;
import exam.model.entity.TSubQuestionEntity;
import exam.model.entity.TUserEntity;
import exam.system.business.AbstractService;
import exam.system.business.BusinessServiceInfo;
/**
 * <p>QuestionAddService</p>
 * <p>Xu ly them cau hoi</p>
 * 
 * @author Phong
 * @version 21/5/2012
 */
public class QuestionAddService extends AbstractService {
	// tQuestionDAO
	private TQuestionDAO tQuestionDAO = new TQuestionDAO();
	// tAnswerDAO
	private TAnswerDAO tAnswerDAO = new TAnswerDAO();
	@Override
	public String executeService(BusinessServiceInfo serviceInfo)
			throws Exception {
		// Lay thong tin cau hoi tu serviceInfo
		TQuestionEntity tQuestionEntity = serviceInfo.getObject(KeyQuestion.T_QUESTION_ENTITY);
		// Lay thong tin dap an tu serviceInfo
		List<TAnswerEntity> tAnswerEntityList = serviceInfo.getList(KeyQuestion.T_ANSWER_ENTITY_LIST);
		if(NullCheckUtil.isNotNull(tQuestionEntity)) {
			tQuestionEntity.setCreateDate(new Date());
			tQuestionEntity.setUpdateDate(new Date());
			tQuestionEntity.setSubQuestionEntity(
					new TSubQuestionEntity(tQuestionEntity.getSubQuestId()));
			tQuestionEntity.setUserEntity(
					new TUserEntity(tQuestionEntity.getUserId()));
			// Goi method them cau hoi: insertQuestion
			int insertQ = tQuestionDAO.insertQuestion(tQuestionEntity);
			if(insertQ != 0) {
				long maxQuestId = tQuestionDAO.selectMaxQuestionId();
				tQuestionEntity.setQuestionId(maxQuestId);
				TAnswerEntity tAnswerEntity = null;
				for(int i = 0; i < tAnswerEntityList.size(); i++) {
					tAnswerEntity = new TAnswerEntity();
					tAnswerEntity.setAnswerContent(tAnswerEntityList.get(i).getAnswerContent());
					tAnswerEntity.setAnswerCorrect(tAnswerEntityList.get(i).getAnswerCorrect());
					tAnswerEntity.setQuestionEntity(tQuestionEntity);
					tAnswerDAO.insertAnswer(tAnswerEntity);
				}
			}
			return ResultPort.SUCCESS;
		}
		return ResultPort.FAIL;
	}

}
